﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace CslData
{
    class Program
    {
        static void Main(string[] args)
        {
            int fromRound = 1;
            int toRound = 29;
            string roundInfoUrlTemplate = "http://www.csl-china.com/league/scheduleanddata?round={0}";
            List<MatchInfo> allMatches = new List<MatchInfo>();
            List<string> strList = new List<string>();
            List<Task> tasks = new List<Task>();
            for (int i = fromRound; i <= toRound; i++)
            {
                Console.WriteLine(i);
                var k = i;//如果不加这句，会一直只下载第30轮的页面
                var task = Task.Factory.StartNew(() =>
                {
                    var str = Parsers.GetMatchInfosStringByActualUrl(String.Format(roundInfoUrlTemplate, k));
                    //Parsers.GetMatchInfosByJsonString(str);
                    strList.Add(str);
             
                });
                tasks.Add(task);
            }
            Task.WhenAll(tasks.ToArray()).Wait();
            Console.ReadLine();
        }
    }

    /// <summary>
    /// 解析器
    /// </summary>
    public class Parsers
    {
        public static string DownloadStringWithLimitedTime(string url, int limit = 1)
        {
            List<Task> tasks = new List<Task>();
            WebClient client = new WebClient();
            string finalResult = null;
            if (limit > 0)
            {
                var task = client.DownloadStringTaskAsync(new Uri(url));
                tasks.Add(task);
                client.DownloadStringCompleted += (a, b) =>
                {
                    if (b.Error == null)
                    {
                        finalResult = b.Result;
                        //return b.Result;
                    }
                    else
                    {
                        finalResult = DownloadStringWithLimitedTime(url, limit - 1);
                    }
                };
                Task.WaitAll(tasks.ToArray());
                //task.Wait();
                return finalResult;
            }
            else
            {
                throw new Exception("Download Times Limit exceeded.");
            }
        }

        /// <summary>
        /// 根据实际url和轮数获得比赛信息列表
        /// </summary>
        /// <param name="url"></param>
        /// <param name="round"></param>
        /// <returns></returns>
        public static List<MatchInfo> GetMatchInfosByActualUrl(string url, int round)
        {
            WebClient client = new WebClient();
            var resultString = GetMatchInfosStringByActualUrl(url);
            var list = JsonConvert.DeserializeObject<List<MatchInfo>>(resultString);
            list.ForEach(matchInfo => matchInfo.RoundNumber = round);
            return list;
        }
        public static string GetMatchInfosStringByActualUrl(string url)
        {
            Console.WriteLine(url);
            WebClient client = new WebClient();
            return client.DownloadString(new Uri(url));
        }

        /// <summary>
        ///  根据url模板和轮数获得比赛信息列表
        /// </summary>
        /// <param name="urlTemplate"></param>
        /// <param name="round"></param>
        /// <returns></returns>
        public static List<MatchInfo> GetMatchInfosByUrlTemplate(string urlTemplate, int round)
        {
            string url = String.Format(urlTemplate, round);
            return GetMatchInfosByActualUrl(url, round);
        }

        public static List<MatchInfo> GetMatchInfosByJsonString(string json)
        {




            throw new NotImplementedException();
        }

    }

    public class Downloader
    {



    }

    /// <summary>
    /// 比赛信息
    /// </summary>
    public class MatchInfo
    {
        /// <summary>
        /// 比赛事件类
        /// </summary>
        public class Event
        {
            public Dictionary<string, string> EventInfos { get; set; } = new Dictionary<string, string>();
            public Dictionary<string, string> EventDetails { get; set; } = new Dictionary<string, string>();
        }
        /// <summary>
        /// 比赛轮数
        /// </summary>
        public int RoundNumber { get; set; }
        /// <summary>
        /// 比赛在该轮的编号
        /// </summary>
        public int MatchIndexInRound { get; set; }
        /// <summary>
        /// 该比赛的比赛事件集合
        /// </summary>
        public List<Event> Events { get; set; } = new List<Event>();
        /// <summary>
        /// 该比赛的细节集合
        /// </summary>
        public Dictionary<string, string> Match { get; set; } = new Dictionary<string, string>();
    }


}
